/*********************************************************************************
 *      Copyright:  (C) 2021 iot
 *                  All rights reserved.
 *
 *       Filename:  ds18b20.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0
 *         Author:  mk
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h> 
#include <dirent.h>
#include <fcntl.h>

#include "ds18b20.h"
#include "../lib/logger.h"


double ds18b20_get_temp(double *temperature)
{
    char                path[100] = "/sys/bus/w1/devices/";  //局部变量存储大概路径
    char                buf1[1024];  
    char                buf2[100];   
    char                *ptr = NULL;  
    int                 fd = -1;  
    int                 rv = -1; 
    int                 flag = 0;  
    DIR                 *dirp;  
    struct dirent       *direntp;

    if((dirp = opendir(path)) == NULL)
    {   
        log_err("Opendir %s error: %s\n",path,strerror(errno));
        return -1; 
    }   

    while((direntp = readdir(dirp)) != NULL)
    {   

        if(strstr(direntp->d_name, "28-"))
        {   
            strncpy(buf2, direntp->d_name, sizeof(buf2));
            flag = 1;
        }
    }

    closedir(dirp);

    if(!flag)
    {
        log_err("Can not find 28- in the path\n");
        return -2;
    }

    strncat(path, buf2, sizeof(path)-strlen(path));
    strncat(path, "/w1_slave",sizeof(path)-strlen(path));

    if((fd = open(path,O_RDONLY)) < 0)
    {
        log_err("Open %s failure: %s\n",path,strerror(errno));
        return -3;
    }

    if((rv = read(fd,buf1,sizeof(buf1))) < 0)
    {
        log_err("Read %s failure；%s\n",path,strerror(errno));
        return -4;
    }

    close(fd);

    if((ptr = strstr(buf1,"t=")) != NULL)
    {
        *temperature = atof(ptr+2)/1000;
        log_nrml("The current temperature: %.2f℃\n", *temperature);
        
    }
    else
    {
        log_err("Can not get the current temperture\n");
        return  -5;
    }




    return 0;
}

